import { baseUrl } from "./baseurl.js";
import { decryptHex,decryptBase64,encryptBase64 } from "@/utils/aes.js"
const install = (Vue) => {
	Vue.prototype.$u.http.setConfig({
		baseUrl: baseUrl,
		dataType: 'json',
		header: {
			'content-type': 'application/json'
		},
	});
	Vue.prototype.$u.http.interceptor.request = async (config) => {
		let token = uni.getStorageSync('riderToken');
		console.log(token);
		// if(config.header && config.header.needToken && token){
		config['header'].publictoken = token;
		console.log(config);
		console.log('requst:',config.data);
		config.data = encryptBase64(JSON.stringify(config.data))
		// }
		// delete config.data.needToken;
		// delete config['header'].justToken;
		return config;      
	}
	
	Vue.prototype.$u.http.interceptor.response = (res) => {
		let data = decryptHex(res + '');
		const dataAxios = JSON.parse(data);
		console.log("response",dataAxios);
		if(dataAxios.code == 200) {
			return dataAxios;
		}else if(dataAxios.code === 401 && /登录/.test(dataAxios.message)){
			Vue.prototype.$u.toast(dataAxios.message);
		}else if(dataAxios.code === 403 && /权限/.test(dataAxios.message)){
			Vue.prototype.$u.toast(dataAxios.message);
			setTimeout(()=>{
				uni.reLaunch({
					url:'/pages/login/login'
				})
			},800)
		}else if(dataAxios.code === 509){
			Vue.prototype.$u.toast(dataAxios.message);
			setTimeout(()=>{
				uni.reLaunch({
					url:'/pages/login/login'
				})
			},800)
			return false;
		}else if(dataAxios.code === 500 && /token/.test(dataAxios.message)){
			Vue.prototype.$u.toast('登录已失效，请重新登录');
			uni.removeStorageSync('riderToken');
			setTimeout(()=>{
				uni.switchTab({
					url:'/pages/login/login'
				})
			},800)
			return false;
		}else if(dataAxios.code === 500){
			Vue.prototype.$u.toast(dataAxios.message);
			return false;
		}else {
			Vue.prototype.$u.toast(dataAxios.message);
			return false;
		}
	}
}

export default {
	install
}